const { Paragraph, TextRun, CheckBox, PageBreak } = require("docx");
const { getAlignment, getIndentValue } = require("../common/utils");
const { generateTextareaField } = require('./textField');
const { generateTextInputField } = require('./textInputField');
const { generateDateTimeGroup } = require('./dateField');
const { generateRadioWithInput } = require('./radioField');
const { generateSignatureDateField } = require('./signatureDateField');

const { generateCriteriaTable } = require('./tableField');
const { generateHorizontalOptions } = require('./horizontalOptionsField');
const { generateVerticalOptions } = require('./verticalOptionsField');
const { generatePasteUnit } = require('./pasteUnitField');
const { generateImageField } = require('./imageField');

// 字段类型到渲染函数的映射
const fieldRenderers = {
    'textareaField': generateTextareaField,
    'textInputField': generateTextInputField,
    'dateTimeGroup': generateDateTimeGroup,
    'radioWithInput': generateRadioWithInput,
    'pasteUnit': generatePasteUnit,
    'signatureDate': generateSignatureDateField,


    'criteriaTable': generateCriteriaTable,
    'horizontalOptions': generateHorizontalOptions,
    'verticalOptions': generateVerticalOptions,
    'imageField': generateImageField,
}

// 获取字段类型
function getFieldType(field) {
    if (field.type) return field.type;
    if (field.value && field.value.options) return 'radioWithInput';
    // 兼容：图片字段可能以 value.image.url 存在
    if (field.value && field.value.image) return 'imageField';
    return field.selectedFieldType;
}

// 渲染单个字段
function renderField(field, baseIndent = 0) {
    const type = getFieldType(field);
    const renderer = fieldRenderers[type];
    
    if (renderer) {
        return renderer(field, baseIndent);
    }
    
    // 默认渲染为复选框
    const finalIndent = getIndentValue(field.value?.alignment, baseIndent);
    
    return [
        new Paragraph({
            indent: { left: finalIndent },
            alignment: getAlignment(field.value?.alignment),
            spacing: { before: 100, after: 50 },
            children: [
                new CheckBox({
                    checked: false,
                    size: 24
                }),
                new TextRun({
                    text: ' ' + (field.value?.label || '默认字段'),
                    size: 21, // 5号字体
                    font: "SimSun" // 宋体
                })
            ]
        })
    ];
}

// 渲染字段列表
function renderFields(fields, baseIndent = 0) {
    const elements = [];
    
    fields.forEach(field => {
        const fieldElements = renderField(field, baseIndent);
        elements.push(...fieldElements);
    });
    
    return elements;
}

// 生成字段（保持向后兼容）
function generateFields(fields, level = 0) {
    if (!fields || !Array.isArray(fields)) {
        return [];
    }
    console.log(fields,'fields')
    const baseIndent = level * 720; // 每层缩进 720 twips (约 1.27cm)

    return fields.flatMap(field => {
        let elements = [];
        console.log(field,'field')
        
        // 渲染普通字段
        elements.push(...renderField(field, baseIndent));
        
        // 递归渲染该字段的子字段
        if (field.children && field.children.length > 0) {
            // 普通字段的子字段也优先使用自己的alignment，没有的话才继承父级的
            const childrenWithAlignment = field.children.map(child => {
                console.log(child.value?.alignment,'普通字段 child.value?.alignment')
                return {
                    ...child,
                    value: {
                        ...child.value,
                        alignment: child.value?.alignment || field.value?.alignment
                    }
                }
            });
            elements.push(...generateFields(childrenWithAlignment, level + 1));
        }
        
        return elements;
    });
}

module.exports = {
    renderField,
    renderFields,
    generateFields,
    getFieldType,
    fieldRenderers
}; 